var patt1=new Array();
patt1[0]='http[s]?://www.google.';
patt1[1]='http[s]?://www.bing.';
patt1[2]='http[s]?://www.google.';
patt1[3]='http[s]?://www.google.';
patt1[4]='http[s]?://search.yahoo.';
patt1[5]='http[s]?://search.yahoo.';
var patt2=new Array();
patt2[0]='&q=';
patt2[1]='?q=';
patt2[2]='?q=';
patt2[3]='#q=';
patt2[4]='&p=';
patt2[5]='?p=';
var patt3='&url';
var loca="klkl";
var fl=0;
var fl1=0;
var post_arr;
// Info of URl is send to Background.html

function changeImgSrc(src, hyp) {
    var hostname=hyp.substr(7);
    var vv=hostname.search('\/');
    hostname=hostname.substring(0,vv);

    src = src.replace(/^\s*|\s*$/,"");
    if((src.indexOf("http") != 0)&&(src.indexOf("\/\/") != 0)){
        if(src.charAt(0) == "\/" || src.charAt(1) == "\/"){
            src = "http://"+hostname + src;
            return src;
        }
        else{
            loc = hyp;
            index = loc.lastIndexOf("\/");
            loc = loc.slice(0, index);
            src = loc +"\/"+ src;
            return src;
        }
    }
    if(src.indexOf("\/\/") == 0) {
        src = "http:"+src;
        return src;
    }
}
$(document).ready(function()
{
	var mila=0;
	for(var i=0;i<patt1.length;i++)
		if(($(location).attr("href")).match(patt1[i]))
		{
			mila=1;
			break;
		}
	if(mila==0)
    {
		if($(location).attr("href").match('http://apps.blinkk.me/extension/fbLogin1.php?'))
			{
				user_mil_gaya();
			}
		else
			{
				var txt="";
                ogtitle = ogdescription = ogimage = ogtype = ogvideo = "";
                if($('meta[property="og:title"]').attr("content")){
                    ogtitle = $('meta[property="og:title"]').attr("content");
                }
                if($('meta[property="og:description"]').attr("content")){
                    ogdescription = $('meta[property="og:description"]').attr("content");
                }
                if($('meta[property="og:image"]').attr("content")){
                    ogimage = $('meta[property="og:image"]').attr("content");
                }
                if($('meta[property="og:type"]').attr("content")){
                    ogtype = $('meta[property="og:type"]').attr("content");
                }
                if($('meta[property="og:video"]').attr("content")){
                    ogvideo = $('meta[property="og:video"]').attr("content");
                }
				if($('meta[name="description"]').attr("content"))
					txt=$('meta[name="description"]').attr("content");
				if($('meta[name="keywords"]').attr("content"))
					txt=txt+" "+$('meta[name="keywords"]').attr("content");

                var imgs = $("img");
                var maxArea = 0;
                var finalImg = "";
                for(k=0;k<imgs.length;k++)
                {
                    if(($(imgs[k]).width()/$(imgs[k]).height() <= 3)&&($(imgs[k]).width()/$(imgs[k]).height() >= 1/3)) {
                        if($(imgs[k]).width() * $(imgs[k]).height() > maxArea) {
                            finalImg = $(imgs[k]).attr("src");    
                            maxArea = $(imgs[k]).width() * $(imgs[k]).height();
                        }
                    }
                }
                finalImg = changeImgSrc(finalImg, window.location.href);
				var title=document.title;

                if(ogtitle == "") {
                    ogtitle = title;
                    ogtype = "manual";
                }
                if(finalImg != "") {
                    ogimage = finalImg;
                }
                var hrefData = {'title':ogtitle, 'description':ogdescription, 'image':ogimage, 'type':ogtype, 'video':ogvideo}; 
                var hrefDataStr=$.toJSON(hrefData);
				var curr=$(location).attr("href");
				var test={ 'hyp': curr , 'txt' : txt,'title':title, 'ogData':hrefDataStr };
                console.debug(test);
				var port = chrome.extension.connect({name: "ses_decide"});
				port.postMessage(test);
			}
    }
	else {
        make_suggestion_div();
    }
});
$("a").live('mousedown',function(event)
	{
	var sent=0;
	var hyplin=$(location).attr("href");
	hyplin=hyplin.toString();
	var k;
	for(k=0;k<patt1.length;k++)
	{
		if(hyplin.match(patt1[k]))
		{
			hyplin=unescape(hyplin);
			var beg=hyplin.indexOf(patt2[k],0);
			if(beg!=-1)
			{
				var another=hyplin.indexOf(patt2[k],beg+2);
				while(another!=-1)
				{
					beg=another;
					another=hyplin.indexOf(patt2[k],another+2);
				}						
				var fin=hyplin.indexOf("&",beg+2);
				if(fin==-1)
					fin=hyplin.length;
				hyplin=hyplin.substring(beg+patt2[k].length,fin);
				for(var c=0;c<hyplin.length;c++)
					hyplin=hyplin.replace("+", " ");
				var curr=event.currentTarget.href;
				curr=unescape(curr);
				curr=curr.toString();
				beg=curr.indexOf(patt3,0);
				fin=curr.indexOf("&",beg+6);
				if( fin>0 && beg>0 )
					curr=curr.substring(beg+5,fin);
				//send hyplin too server ajax_maro();
				if(!curr.match(patt1[k]))
				{
					//alert(curr);
					if( curr.match("http://") || curr.match("https://") || curr.match("ftp://") )
						{
						hyplin = jQuery.trim(hyplin);
						var test={ 'one': curr , 'two' : hyplin , 'mode' : 1 };
						sent=1;
						var port = chrome.extension.connect({name: "en"});
						port.postMessage(test);
					}
				}
			}
		}
	}
	if(sent==0)
	{
		hyplin=$(location).attr("href");
		var to_send=this.innerText;
		var curr=event.currentTarget.href;
		var test={ 'one': curr, 'two' : hyplin ,'mode' : 2, 'to_sto': to_send };
		sent=1;
		var port = chrome.extension.connect({name: "en"});
		port.postMessage(test);
	}
});
$('.callmakePost').live('click',function()
{
	$('#audin003').remove();
	$('body').append('<div id="audin003" style="border:2px solid #CCC;padding:10px;background-color:#FFFFFF;height:550px;overflow:scroll;width:600px;top:50px;right:400px;position:fixed;z-index:100"><div style="position:absolute;left:0px;top:0px" onclick="document.getElementById(\'audin003\').style.display=\'none\';"><img style="z-index:10000" src="http://floost.com/static/default/images/x.png"/></div></div>');
	var val=this.id;
	val=val.substring(3);
	val=parseInt(val);
	var tot_post=post_arr_creator_hyp(post_arr[val]);
	i=0;
	var heading="";
	$('#audin003').append('<ul class="append_here"></ul>');
	var asd = new RegExp("\n","g");
	while(i<tot_post.length)
		{
		heading='<div class="one"><div class="hyp_head"><b><a href="'+tot_post[i].hyp+'" target="_blank">'+tot_post[i].hyp+'</a></b></div></div>';
		var txt=tot_post[i].post.replace(asd,'<br/>');
		var to_append='<li><div class="main_post">'+heading+'<div class="subpost">'+txt+'</div></div></li>';
		$('#audin003 .append_here').append(to_append);
		i++;
		}
});
$("#audin009").live('click',function()
{

			fl1=0;
			fl=0;
			$("#audin007").animate({width:'20px'},1000);
			$("#audin007").css({border:'0px solid #CCC'});
			$('#audin00223').remove();
			$('#audin008').css({display:''});
			$('#audin009').css({display:'none'});

});

function searchCreation(flagVal) {
	post_arr=null;
	post_arr=new Array();
	if(fl1==0)
	{
		//alert("entered fl1");
		if(fl==1)
			return;
		fl=0;
		$('#audin00223').remove();
		var hyplin=$(location).attr("href");
		hyplin=hyplin.toString();
		var k;
		for(k=0;k<patt1.length;k++)
		{
			if(hyplin.match(patt1[k]))
			{
			hyplin=unescape(hyplin);
			var beg=hyplin.indexOf(patt2[k],0);
			if(beg!=-1)		//can later include other(image, from inside someother website)searches too 
				{
				var another=hyplin.indexOf(patt2[k],beg+2);
				while(another!=-1)
					{
					beg=another;
					another=hyplin.indexOf(patt2[k],another+2);
					}						
				var fin=hyplin.indexOf("&",beg+2);
				if(fin==-1)
					fin=hyplin.length;
				hyplin=hyplin.substring(beg+3,fin);
				for(var c=0;c<hyplin.length;c++)
					hyplin=hyplin.replace("+", " ");
				}
			}
		}
		var flaggg=0;
		for(k=0;k<patt1.length;k++)
			if(hyplin.match(patt1[k]))
				flaggg=1;
		if(flaggg==0)
		{
			var test=new Object();
			test.sear=hyplin;
            //console.debug(test);
			//alert(hyplin);
			var port = chrome.extension.connect({name: "server_pe_bhejo"});
			port.postMessage(test);
			port.onMessage.addListener(function(msg)
			{
				var to_disp=$.evalJSON(msg.answer);
				if(to_disp==false)
				{

                    if(flagVal == "click") {
					    var to_append='<div id="audin00223"style="margin-left:10px;margin-top:10px"><h3>Nothing found</h3></div>';
					    $('#audin007').append(to_append);
					    $("#audin007").css({border:'2px solid #CCC'});
					    $("#audin007").animate({width:'400px'},1000, function() {	$('#audin009').css({display:''});});
                    }
				}
				else
				{
					var to_append="";
					var t=0;
					var numb_sug=to_disp.length;
                    var numberOfUsers = new  Object();
                    var distinctUsers = 0;
					while(t<numb_sug)
					{
						var to_pass=t;
                        if(numberOfUsers[to_disp[t].fb_id] == undefined) {
                            numberOfUsers[to_disp[t].fb_id] = 1;
                            distinctUsers++;
                        }else{
                        }
						var photo=to_disp[t].photo_url;
						var searchKeyword=to_disp[t].session_name;
						var usr_name=to_disp[t].user_name[0];
						var spen_time=to_disp[t].time_spent/60000;
                        console.debug(to_disp[t]);
						if(spen_time<1&&spen_time>0)
                        {
                            spen_time=1;
                        }
						post_arr[t]=$.evalJSON(to_disp[t].hyp_obj);
						var ask;
						var flag_11=0;
						for(ask=0;ask<post_arr[t].length;ask++)
							if(post_arr[t][ask].post!=null)
								if(post_arr[t][ask].post.length>0)
								{
									flag_11=1;
								}
						if(flag_11==0)
						{
							t++;
							continue;
						}
						to_append=to_append+'<div id="audin_'+t+'"><div style="display:block;"><div style="float:left;margin-right:10px;margin-left:10px"><div class="photo"><img src="'+photo+'"></img></div></div><div style="float:left; margin-right:10px"><div style="float:left; margin-right:10px"><div><b>'+searchKeyword+'</b></div><div class="name">'+usr_name+'</div>  <div class="time_s">Time Spent: '+Math.round(spen_time,0)+' mins</div>    </div><div style="float:right"><a id="aud'+to_pass+'" class="callmakePost"href="javascript:void();">Show Post</a></div></div></div></div><div style="clear:both">&nbsp;</div>';
						t++;
					}

                    if(flagVal == "general") { 
                        if(distinctUsers == 1) {
                            to_append= distinctUsers+" friend is interested in this topic";
                        }else{
                            to_append= distinctUsers+" friends are interested in this topic";
                        }
                        to_append='<div style="cursor:pointer;background-color:#ccc;padding:10px;position:fixed;top:200px;right:80px;" id="mmkk">'+to_append+'</div>';
                        $('body').append(to_append);
                    }

                    if(flagVal == "click") {
    					to_append='<div id="audin00223" style="max-height=400px">'+to_append+'</div>';
    					$('#audin007').append(to_append);
    					$('#audin008').css({display:'none'});
    				
    					$("#audin007").animate({width:'400px'},1000, function() {	$('#audin009').css({display:''});});
    					$("#audin007").css({border:'2px solid #CCC'});
    					$("#audin00223").css({overflow:'auto'});
                    }
				}
			});
			
		}
		else
		{
            if(flagVal == "click") {
                var to_append="Search something";
                to_append='<div style="background-color:red;padding:10px;position:fixed;top:200px;right:80px;" id="mmkk">'+to_append+'</div>';
                $('body').append(to_append);
                setTimeout("$('#mmkk').animate({opacity:'0'},500,function(){$('#mmkk').remove();})",800);
            } 
		}
	fl1=0;
	}
}

$("#mmkk").live('click',function()
{
    setTimeout("$('#mmkk').animate({opacity:'0'},500,function(){$('#mmkk').remove();})",800);
    searchCreation("click");
});


$("#audin008").live('click',function()
{
    searchCreation("click");
});
function make_suggestion_div()
{
	if(loca!=$(location).attr("href"))
	{
		fl=0;
		$('#audin007').remove();
		loca=$(location).attr("href");
		var h=$(document).height();
		h=h*.5;
		var style_ele='style="width:20px;background-color:#FFFFFF;position:fixed;right:0px;top:'+200+'px;padding:10px 10px 0 10px;border:0px solid #CCCCCC;min-height:95px"';
		var to_append='<div id="audin007" '+style_ele+'><div id="audin009" style="display:none"><img style="position:absolute;left:-10px;top:-10px;z-index:10" src="http://floost.com/static/default/images/x.png"/></div><div style="float:left" id="audin008"><img src="http://floost.com/static/default/images/open.png"/></div></div>';
		$('body').append(to_append);
        searchCreation("general");
	}
	setTimeout('make_suggestion_div()',500);
}
function user_mil_gaya()
{
	if(document.getElementById('userImg')!=null)
	{
		var post=new Object();
		post.img=document.getElementById('userImg').src;
		post.name=document.getElementById('name').innerHTML;
		post.id=document.getElementById('id').innerHTML;
		post.record="true";
		var to_send=new Object();
		to_send.one=post;
		to_send.two="http://floost.com/facebook/register?redirectToForm=1&url=http://floost.com/register/register";
		$('#fetch').remove();
		var port = chrome.extension.connect({name: "set_user"});
		port.postMessage(to_send);
	}
	else
		{
		if($('#id')!=null)
			$('body').append('<h3 id="fetch">Fetching data..</h3>');
		setTimeout('user_mil_gaya();',1000);
		}
}
function tutorial(val)
{
	$('#rem').remove();
	switch(val)
	{
		case 1:$('#tut').append('<div id="rem">Bored with using bookmarks use this to view ur history on basis of content. This extension sorts ur history on basis of content and what you wanted out of the page or read from it. </div>');
		break;
		case 2:$('#tut').append('<div id="rem">Creating posts just one click away. Just browse through webpages give some keywords and ur post gets generated.</div>');
		break;
		case 3:$('#tut').append('<div id="rem">You also get acess to online researches done by others. Just search for it and u will get suggestions of people with thier reasearch works.</div>');
		break;
		case 4:$('#tut').append('<div id="rem">Lets you analyse your online research on a timeline basis. The content, timestamp,frequencyof use and the amount of time  u spent on a specific content .!! or webpages or searches .</div>');
		break;	
	}
	if(val<4)
		setTimeout('tutorial('+(val+1)+')',10000);
}
function sort_list1(a,b)
{
	return (a.score-b.score);
}
function post_arr_creator_hyp(list_hyp)
{
	var tot_post=new Array();
	for(var i=0;i<list_hyp.length;i++)
	{
		var temp=list_hyp[i];
		txt="";
		if(temp.post==null)
		{
			continue;
		}
		for(var j=0;j<temp.post.length;j++)
		{
			if(temp.post[j].txt)
				txt=txt+temp.post[j].txt;
			else if(temp.post[j].src)
				txt=txt+'<img style="margin:5px" src='+temp.post[j].src+'></img>';
		}
		/*sub-post created in txt*/
		var pos_obj=new Object();
		pos_obj.post=txt;
		pos_obj.score=temp.sum;
		pos_obj.hyp=list_hyp[i].hyplin;
		tot_post.push(pos_obj);
	}	
	tot_post=tot_post.sort(sort_list1);
	return tot_post;
}
